package com.ba.base.utils

import android.app.Activity
import android.content.Context
import com.alibaba.android.arouter.launcher.ARouter
import com.ba.base.api.ApiAuth
import com.ba.base.model.vo.TokenUserEntity
import com.ba.base.model.vo.UserEntity
import qsos.lib.base.utils.ActivityManager
import qsos.lib.base.utils.ToastUtils

/**
 *
 * 登录成功后续处理流程
 */
object LoginResultHelper {

    fun success(
        context: Context,
        result: TokenUserEntity,
        password: String,
        mobile: String,
        home: Boolean = true
    ) {
        ApiAuth.status = ApiAuth.STATUS.LOGIN
        // 同步token
        ApiAuth.bearer = result?.access_token ?: ""
        // 保存用户数据
        var userEntity = UserEntity()
        userEntity.access_token = result.access_token
        userEntity.refreshToken = result.refresh_token
        userEntity.jobNo = result.user?.jobNo
        userEntity.realName = result.user?.realName
        userEntity.idCard = result.user?.idCard
        userEntity.sex = result.user?.sex
        userEntity.password = password
        userEntity.roleName = result.roleName
        userEntity.userId = result.user?.userId
        ApiAuth.pwd = password
        ApiAuth.phone = mobile
        userEntity.mobile = mobile
        SharedPreUtils.saveUserInfo(context, userEntity)
        if (home) {
            /**跳转首页*/
            ActivityManager.finishAllButNotMe(context as Activity)
            ARouter.getInstance().build("/app/main").navigation()
            context.finish()
        }
    }

    fun failed(
        context: Context,
        home: Boolean = true,
        finish: Boolean = false,
        toast: Boolean = true
    ) {
        clear(context)
        if (toast) {
            ToastUtils.showToast(context, "您未登录，请前往【我的页面】进行登录后操作")
        }
        if (home) {
            ARouter.getInstance().build("/app/login").navigation()
        }
        if (finish) {
            (context as Activity).finish()
        }
    }

    fun loginOut(context: Context) {
        clear(context)
        SharedPreUtils.clearUserInfo(context)
        SharedPreUtils.clear(context)
        ARouter.getInstance().build("/app/login").navigation()
        (context as Activity).finish()
    }

    private fun clear(context: Context) {
//        SharedPreUtils.clearUserInfo(context)
//        ApiAuth.status = ApiAuth.STATUS.NULL
//        ApiAuth.bearer = ""
//        ApiAuth.userId = ""
//        ApiAuth.deptId = -1
//        ApiAuth.phone = ""
//        ApiAuth.user = null
    }
}